package com.likou;

import java.util.Deque;
import java.util.LinkedList;

public class q32 {

    public int longestValidParentheses(String s) {
        Deque<Integer> deque = new LinkedList<>();
        int ans = 0;

        deque.push(-1);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(') {
                deque.push(i);
            } else {
                deque.pop();

                if (deque.peek() != null) {
                    ans = Math.max(ans, i - deque.peek());

                } else {
                    deque.push(i);

                }

            }
        }

        return ans;
    }
}
